package com.cslc.mp.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

import com.cslc.mp.constant.MpApi;
import com.cslc.mp.constant.MpInfo;
import com.cslc.mp.dao.DAOFactory;
import com.cslc.mp.service.CoreServiceFactory;

public class ScanServlet extends HttpServlet {

	private static Logger logger = Logger.getLogger(ScanServlet.class.getName());

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//TODO 要加上签名验签，时间戳等安全手段
		String flag = null;
		flag = request.getParameter("flag");
		
		//用户点击确认或取消绑定按钮后的GET请求
		if(flag != null) {
			HttpSession session = request.getSession();
			String openid = (String) session.getAttribute("openid");
			String terminalNo = (String) session.getAttribute("terminalNo");
			logger.debug("flag: " + flag + "\n" + "openid: " + openid + "\n" + "终端编码： " + terminalNo);
			
			if(flag.equals("confirm") && DAOFactory.getIUserDAOInstance().bindUser(openid, terminalNo)) {
				response.sendRedirect(MpInfo.HOST + "/bind_success.jsp");
				logger.debug(terminalNo + " 和 " + openid + "绑定成功");
			}
			else if(flag.equals("cancel")) {
				response.sendRedirect(MpInfo.HOST + "/bind_error.jsp");
				logger.debug(terminalNo + "和" + openid + "绑定失败");
			}
			else 
			logger.error("未知错误");
		}
		
		//扫码事件触发的请求，无flag参数
		else {
			JSONObject jsonObject = null;
			String openid = null;
			String code = request.getParameter("code");
			String state = request.getParameter("state");
			//通过code获取openid
			jsonObject = CoreServiceFactory.getInstance().oauth2AcessGet(code);
			openid = jsonObject.getString("openid");
			//将openid存入session中
			HttpSession session = request.getSession();
			session.setAttribute("openid", openid);
			session.setAttribute("state", state);
			//测试session
			String sessionId = request.getSession().getId();
			logger.debug(sessionId);
			//forward到绑定确认界面
			RequestDispatcher rd = request.getRequestDispatcher("/scan_bind.jsp");
			rd.forward(request, response);
		}
		
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
